<template>
	<div class="proxy-creation">
		<div class="search-content">
			<a-form layout="vertical">
				<a-row :gutter="24">
					<a-col class="gutter-row" :span="8">
						<a-form-item
							:colon="false"
							:label="$t('delegate.agentTitle', '委托人')"
						>
							<ok-employee-select
								.person-format="tenantDetail.person_format"
								.dept-full-path="tenantDetail.secrecy"
								.remote-method="remoteMethod"
								organization-type="INTERNAL"
								width="100%"
								.value="entrustedValueData"
								.placeholder="
									$t('delegate.proxyAgent', '可使用姓名或邮箱搜索添加委托人')
								"
								.update="updateSelectEntrusted"
								ref="entrustedValueRef"
							></ok-employee-select>
						</a-form-item>
					</a-col>
					<a-col class="gutter-row" :span="8">
						<a-form-item
							:colon="false"
							:label="$t('delegate.consignee', '被委托人')"
						>
							<ok-employee-select
								.person-format="tenantDetail.person_format"
								.dept-full-path="tenantDetail.secrecy"
								.remote-method="remoteMethod"
								organization-type="INTERNAL"
								width="100%"
								.value="CoordinatorValueData"
								.placeholder="
                                    $t('delegate.proxyAgent', '可使用姓名或邮箱搜索添加被委托人')
                                "
								.update="updateSelect"
								ref="CoordinatorValueRef"
							></ok-employee-select>
						</a-form-item>
					</a-col>
					<a-col class="gutter-row" :span="8">
						<a-form-item
							:colon="false"
							:label="$t('delegate.CommissioningTime', '委托代理时间')"
						>
							<a-range-picker
								v-model:value="DefinitiontimeValueData"
								format="YYYY-MM-DD"
								:placeholder="[
									$t('informationPortal.StartTime', '起始时间'),
									$t('informationPortal.announcedEndPlaceholder', '结束时间'),
								]"
								@change="pickerChange"
							>
								<template #suffixIcon>
									<i class="low-code iconrili1" />
								</template>
							</a-range-picker>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="24" class="secondRow">
					<a-col class="gutter-row" :span="20">
						<a-form-item :colon="false" :label="$t('delegate.status', '状态')">
							<a-radio-group
								v-model:value="formData.status"
								@change="ifChangeStatus = true"
							>
								<a-radio value="FORMAL">{{
									$t('delegate.Using', '生效中')
								}}</a-radio>
								<a-radio value="PRE_FORMAL">{{
									$t('delegate.noEffect', '待生效')
								}}</a-radio>
								<a-radio value="COMPLETED">{{
									$t('delegate.hasFinished', '已完成')
								}}</a-radio>
								<a-radio value="DRAFT">{{
									$t('delegate.draft', '草稿')
								}}</a-radio>
								<a-radio value="DELETED_DRAFT">{{
									$t('delegate.hasDeletedDraft', '已删除草稿')
								}}</a-radio>
								<a-radio value="DELETED">{{
									$t('delegate.hasDeletedDelegate', '已删除委托')
								}}</a-radio>
							</a-radio-group>
						</a-form-item>
					</a-col>
				</a-row>
				<div class="buttons">
					<a-button type="primary" @click="getList">{{
						$t('informationPortal.search', '查询')
					}}</a-button>
					<a-button class="reset-button" @click="reset">{{
						$t('informationPortal.reset', '重置')
					}}</a-button>
				</div>
			</a-form>
		</div>
		<div class="list-content">
			<a-button type="primary" @click="add">{{
				$t('delegate.add', '新增')
			}}</a-button>
			<a-table
				:columns="columns"
				:data-source="dataSource"
				:pagination="false"
				:loading="loading"
				size="small"
				bordered
			>
				<template #consigner="{ record }">
					<div class="person-content" :key="record.consigner">
						<ok-person-cell
							width="24px"
							height="24px"
							.person-info="record.consigner"
						></ok-person-cell>
						<EllipsisTooltip :title="record.consigner?.employee_name" />
					</div>
				</template>
				<template #agent_info="{ record }">
					<div class="person-content" :key="record.agent_info">
						<ok-person-cell
							width="24px"
							height="24px"
							.person-info="record.agent_info"
						></ok-person-cell>
						<EllipsisTooltip :title="record.agent_info?.employee_name" />
					</div>
				</template>
				<template #time="{ record }">
					<span>
						{{ moment(record.start_date).format('YYYY-MM-DD') }} ~
						{{ moment(record.end_date).format('YYYY-MM-DD') }}
					</span>
				</template>
				<template #operate="{ record }">
					<i
						title="查看"
						class="low-code iconliulan1"
						@click="operate(record, 'view')"
					></i>
					<i
						title="编辑"
						class="low-code iconbianji6-Blue"
						v-if="!notEdit.includes(nowStatus)"
						@click="operate(record, 'edit')"
					></i>
					<i
						title="删除"
						class="low-code iconlajitong"
						v-if="!notEdit.includes(nowStatus)"
						@click="del(record)"
					></i>
				</template>
			</a-table>
			<a-pagination
				v-model:current="pagination.page_index"
				v-model:page-size="pagination.page_size"
				:page-size-options="pagination.pageSizeOptions"
				:total="pagination.total"
				:show-total="(total:number) => `共 ${total} 条数据`"
				show-size-changer
				@change="onChange"
				@showSizeChange="onChange"
			>
				<template #buildOptionText="props">
					<span>
						{{ props.value }}{{ $t('informationPortal.item', '条') }}/{{
							$t('informationPortal.page', '页')
						}}
					</span>
				</template>
			</a-pagination>
		</div>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, createVNode } from 'vue'
import { useRouter } from 'vue-router'
import useModel from './hooks/useModel'
import moment from 'moment'
import { message, Modal } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { apiInit } from '@/services'
import EllipsisTooltip from '@/entry_desktop/components/EllipsisTooltip'
import { i18n } from '@/locales'
const { $t } = i18n
let tenantDetail: any = reactive({})
const entrustedValueData = ref([])
const entrustedValueRef = ref()
const CoordinatorValueData = ref([])
const CoordinatorValueRef = ref()
const router = useRouter()
const api = apiInit()
const formData = reactive<typing.delegate.DelegatePageRequest>({
	consigner_id: '',
	agent_id: '',
	start_date: '',
	end_date: '',
	status: 'FORMAL',
})
const ifChangeStatus = ref(false)
const loading = ref(false)
const DefinitiontimeValueData = ref([])
const columns = [
	{
		title: $t('informationPortal.SerialNumber', '序号'),
		align: 'center',
		customRender: ({ index }: any) => `${index + 1}`,
	},
	{
		title: $t('delegate.agentTitle', '委托人'),
		dataIndex: 'consigner',
		slots: { customRender: 'consigner' },
	},
	{
		title: $t('delegate.consignee', '被委托人'),
		dataIndex: 'agent_info',
		slots: { customRender: 'agent_info' },
	},
	{
		title: $t('delegate.CommissioningTime', '委托代理时间'),
		dataIndex: 'time',
		slots: { customRender: 'time' },
	},
	{
		title: $t('informationPortal.creator', '创建人'),
		dataIndex: 'creator',
		customRender: ({ record }: any) => `${record?.creator?.employee_name}`,
	},
	{
		title: $t('delegate.createTime', '创建时间'),
		dataIndex: 'create_time',
	},
	{
		title: $t('delegate.updater', '更新人'),
		dataIndex: 'operator',
		customRender: ({ record }: any) => `${record?.operator?.employee_name}`,
	},
	{
		title: $t('delegate.updateTime', '更新时间'),
		dataIndex: 'u_date',
	},
	{
		title: $t('delegate.operate', '操作'),
		slots: { customRender: 'operate' },
	},
]
type paginationType = {
	page_index: number
	page_size: number
	pageSizeOptions: Array<string>
	total: number | undefined
}
const pagination = reactive<paginationType>({
	page_index: 1,
	page_size: 10,
	pageSizeOptions: ['10', '20', '30', '40', '50'],
	total: 1,
})
const onChange = (pageIndex: number, pageSize: number) => {
	if (pageSize !== pagination.page_size) {
		pagination.page_index = 1
		pagination.page_size = pageSize
	} else {
		pagination.page_index = pageIndex
	}
	getList()
}
const dataSource: any = ref([])
const nowStatus: any = ref(formData.status)
const notEdit: any = ['COMPLETED', 'DELETED_DRAFT', 'DELETED']
const { getEmployeesInfo } = useModel()
const remoteMethod = async (value: string) => {
	return await getEmployeesInfo(value, true)
}
const updateSelectEntrusted = (ids: any) => {
	formData.consigner_id = ids[0]
}
const updateSelect = (ids: any) => {
	formData.agent_id = ids[0]
}
const reset = () => {
	formData.consigner_id = ''
	formData.agent_id = ''
	formData.start_date = ''
	formData.end_date = ''
	formData.status = 'FORMAL'
	entrustedValueData.value = []
	entrustedValueRef.value.clear()
	CoordinatorValueData.value = []
	CoordinatorValueRef.value.clear()
	DefinitiontimeValueData.value = []
	getList()
}
const add = () => {
	router.push('/add_delegation')
}
const getList = async () => {
	loading.value = true
	if (ifChangeStatus.value) {
		pagination.page_index = 1
	}
	nowStatus.value = formData.status
	let res = await api.delegateAuto.ListAdminDelegatePrivateV3Ego_apiPOST({
		payload: {
			...formData,
			page_index: pagination.page_index,
			page_size: pagination.page_size,
		},
	})
	pagination.total = res.data?.page?.total
	dataSource.value = res.data?.rows
	ifChangeStatus.value = false
	loading.value = false
}
const operate = (item: any, mode: string) => {
	router.push({
		name: 'add_delegation',
		query: {
			id: item.id,
			send_msg: item.send_msg,
			employee_id: item.agent_info.employee_id,
			consigner_id: item.consigner.employee_id,
			start_date: moment(item.start_date).format('YYYY-MM-DD HH:mm:ss'),
			end_date: moment(item.end_date).format('YYYY-MM-DD HH:mm:ss'),
			status: nowStatus.value,
			start_dept_id: JSON.stringify(
				item.start_dept
					? item.start_dept.map((item: any) => item.department_id)
					: undefined
			),
			has_child: item.has_child,
			mode,
		},
	})
}
const del = async (item: any) => {
	Modal.confirm({
		icon: createVNode(ExclamationCircleOutlined),
		content: $t('delegate.deleteTip', '确认删除此委托？'),
		okText: $t('personalCenter.confirm', '确认'),
		cancelText: $t('personalCenter.cancel', '取消'),
		onOk() {
			return new Promise(async (resolve, reject) => {
				let res = await api.delegateAuto.DeleteDelegatePrivateV3Ego_apiPOST({
					payload: { id: item.id },
				})
				if (res.code === '000000') {
					message.success('删除成功')
					getList()
				}
				setTimeout(Math.random() > 0.5 ? resolve : reject, 1000)
			}).catch(() => console.log('Oops errors!'))
		},
	})
}
const pickerChange = (value: any, dateString: string[]) => {
	formData.start_date = dateString[0] ? `${dateString[0]} 00:00:00` : ''
	formData.end_date = dateString[1] ? `${dateString[1]} 23:59:00` : ''
}
onMounted(() => {
	getList()
})
</script>

<style lang="less" scoped>
.proxy-creation {
	padding-top: 10px;
	& > div {
		width: 100%;
		box-shadow: 4px 0px 8px rgba(0, 0, 0, 0.03);
		border-radius: 8px;
		background-color: #fff;
		padding: 24px 16px;
		position: relative;
		margin-bottom: 16px;
	}
	.search-content {
		padding-bottom: 20px;
		.ant-calendar-picker {
			width: 100%;
		}
		.buttons {
			position: absolute;
			right: 18px;
			bottom: 20px;
			.reset-button {
				margin-left: 10px;
			}
		}
		/deep/ label.ant-radio-wrapper:hover {
			background-color: transparent !important;
		}
		:deep(.ant-picker-range) {
			width: 100%;
			.ant-picker-active-bar {
				display: none;
			}
		}
		.secondRow .ant-form-item {
			margin-bottom: 0;
		}
	}
	.list-content {
		padding-top: 12px;
		height: calc(100vh - 358px);
		margin-bottom: 0;
		& > .ant-btn {
			margin-bottom: 12px;
		}
		.low-code {
			color: @rok-primary-color;
			margin-right: 10px;
			cursor: pointer;
			&:hover {
				color: @rok-primary-hover-color;
			}
		}
		/deep/ .ant-table {
			max-height: calc(100vh - 494px);
			overflow-y: scroll;
			&.ant-table-small .ant-table-tbody > tr > td {
				padding: 7px 8px;
			}
			thead th {
				line-height: 32px;
			}
		}
		.ant-pagination {
			position: absolute;
			right: 21px;
			margin-top: 24px;
		}
		.person-content {
			display: flex;
			align-items: center;
			ok-person-cell {
				margin-right: 4px;
			}
		}
	}
}
</style>
